JavaScript and Ajax Tips & Tutorials
make ajax call from JavaScript
Ajax is used to make asynchronous communication with the server.
Ajax is used to read data from the server and update the page or send data to the server without affecting the current client page.
Ajax is a programming concept.
Below are some ways to make Ajax calls in JavaScript.
1. Using the XMLHttpRequest object
2. Using jQuery
3. Using fetch() API
Approach 1: Using the XMLHttpRequest object
Use the XMLHttpRequest object to make an Ajax call.
The XMLHttpRequest() method creates an XMLHttpRequest object which is used to make a request with the server.
Syntax:
let xhttp = new XMLHttpRequest();
function run() {
// Creating Our XMLHttpRequest object
let xhr = new XMLHttpRequest();
// Making our connection
let url = 'https://jsonplaceholder.typicode.com/todos/1';
xhr.open("GET", url, true);
// function execute after request is successful
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}
// Sending our request
xhr.send();
}
run();
Approach 2: Using jQuery
It is used as a replacement for all approaches which are not working to make ajax calls.
Syntax:
$.ajax({arg1: value, arg2: value, ... });
Parameter: It takes a configuration file that configures the URL, type, and function to call when we get our response or if error, etc.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js">
</script>
</head>
<body>
<script>
function ajaxCall() {
$.ajax({
// Our sample url to make request
url:
'https://jsonplaceholder.typicode.com/todos/1',
// Type of Request
type: "GET",
// Function to call when to
// request is ok
success: function (data) {
let x = JSON.stringify(data);
console.log(x);
},
// Error handling
error: function (error) {
console.log(`Error ${error}`);
}
});
}
ajaxCall();
</script>
</body>
</html>
Approach 3: Using fetch() API
This API makes a request to the server and gets the result as a promise which is resolved to the string.
Syntax:
fetch(url, {config}).then().catch();
Parameter: It takes URL and config of the request as parameters.
We will configure the data required and make the request to the server.
Since it is a resolved promise we use then() function and the catch() function to create output for the result.
In response, we get the string that we print.
// Url for the request
let url = 'https://jsonplaceholder.typicode.com/todos/1';
// Making our request
fetch(url, { method: 'GET' })
.then(Result => Result.json())
.then(string => {
// Printing our response
console.log(string);
// Printing our field of our response
console.log(`Title of our response : ${string.title}`);
})
.catch(errorMsg => { console.log(errorMsg); });
Example
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
</body>
</html>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
**Create Keyboard Shortcuts for Web Apps with JavaScript
For a long time, Web apps were not considered an viable alternative to desktop apps, and one of the primary reasons was the lack of keyboard shortcuts. You can change that using JavaScript.
An Introduction to Event Handling in jQuery
Leverage the power of the jQuery Event API to handle events for your DOM elements.
Building a Style Sheet Switcher with JavaScript
Because JavaScript is a client-side scripting language, it is ideally suited to the task of building a style sheet switcher.
Build a Context Menu with jQuery and CSS
Bring desktop app functionality to your Web apps by using jQuery and CSS to implement context menus for your users.
Building an Ajax-driven File Uploader
Try a file-upload solution that uses Ajax to provide continuous feedback to the user as the file is being uploaded to the server.
Combine Ajax and JSON to Transmit Complex Presentation Data
Learn how to combine Ajax and JSON to override the browser's default locale and perform retrievals of complex data.
Form Validation using jQuery
There are as many ways to implement form validation as there are opinions of the best way to do it. This article discusses client-side validation using jQuery's validation plugin. That is, we will use JavaScript
to validate the fields before submitting the form to the server.
Example
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("theHint").innerHTML = "";
return;
} else {
var xmlReq = new XMLHttpRequest();
xmlReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("theHint").innerHTML = this.responseText;
}
};
xmlReq.open("GET", "gethint.php?q=" + str, true);
xmlReq.send();
}
}
</script>
</head>
<body>
<form action="">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="theHint"></span></p>
</body>
</html>